package com.view.comp.ImageCroping.ui
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	
	public class ImageUploader extends EventDispatcher
	{
		public function ImageUploader()
		{
			
		}
		
		public static const FILE_LOADED_EVENT:String 			= 'file_loaded_event';
		public static const FILE_BROWSE_CANCELED_EVENT:String 	= 'file_browse_canceled_event';
		
		private var fileReference:FileReference = new FileReference();
		public var imageData:ByteArray = null;
		public var imageData2:ByteArray = null;
		public var uploadLimitInMB:Number = 2;
		
		public function onBrowseClicked(event:MouseEvent):void 
		{
			var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png;*.jpeg");
			fileReference.addEventListener(Event.SELECT, onFileSelected);
			fileReference.addEventListener(Event.CANCEL, onSelectCancel);
			fileReference.browse([imagesFilter]);
		}

		private function onFileSelected(event:Event):void 
		{
			var fileSize:Number = fileReference.size / (1024 * 1024);
			if(fileSize > uploadLimitInMB){
				Alert.show('Upload limit is ' + uploadLimitInMB.toString() + ' MB.','Warning');
				cancelUpload();
				return;	
			}
			
			imageData = null;
			fileReference.removeEventListener(Event.SELECT, onFileSelected);
			fileReference.removeEventListener(Event.CANCEL, onSelectCancel);
			fileReference.addEventListener(Event.COMPLETE, onFileLoaded);
			fileReference.load();
		}
		
		private function onSelectCancel(event:Event):void
		{
			cancelUpload();
		}
		
		private function cancelUpload():void
		{
			imageData = null;
			fileReference.removeEventListener(Event.SELECT, onFileSelected);
			fileReference.removeEventListener(Event.CANCEL, onSelectCancel);
			dispatchEvent( new Event(FILE_BROWSE_CANCELED_EVENT) );
		}
		
		private function onFileLoaded(event:Event):void
		{
			fileReference.removeEventListener(Event.COMPLETE, onFileLoaded);

			imageData = fileReference.data;
			imageData2 = fileReference.data;
			dispatchEvent( new Event(FILE_LOADED_EVENT) );
		}
		
		
	}
}